package main

import (
	"errors"
	"image"
	_ "image/jpeg"
	_ "image/png"
	"net/http"
	"os"
	"path/filepath"
)

type AppAsset struct {
	Path string
	Ext  string
	Kind string
	URL  string
}

func GetAsset(kind string, list []*AppAsset) *AppAsset {
	for _, item := range list {
		if item.Kind == kind {
			return item
		}
	}
	return nil
}

func LoadAppAssets(localPath string) []*AppAsset {
	matches, err := filepath.Glob(localPath)
	if err != nil {
		return []*AppAsset{}
	}

	var list = []*AppAsset{}

	for _, path := range matches {
		ext := filepath.Ext(path)
		kind := ASSET_KIND_OTHERS

		err, width, _ := isImage(path)

		if err == nil {
			if width > 72 {
				kind = ASSET_KIND_FULL_SIZE_IMAGE
			} else {
				kind = ASSET_KIND_DISPLAY_IMAGE
			}
		}

		if ext == ".ipa" {
			kind = ASSET_KIND_SOFTWARE_PACKAGE
		}

		if ext == ".plist" {
			kind = ASSET_KIND_PLIST
		}

		asset := &AppAsset{
			Path: path,
			Ext:  ext,
			Kind: kind,
		}

		list = append(list, asset)
	}

	return list
}

func isImage(path string) (err error, width int, height int) {
	file, err := os.Open(path)

	if err != nil {
		return err, 0, 0
	}

	defer func() {
		file.Close()
	}()

	buff := make([]byte, 512) // why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
	_, err = file.Read(buff)

	if err != nil {
		return err, 0, 0
	}

	fileType := http.DetectContentType(buff)

	_, err = file.Seek(0, 0)
	if err != nil {
		log.Error(err)
	}

	switch fileType {
	case "image/jpeg", "image/jpg", "image/gif", "image/png":
		img, _, err := image.DecodeConfig(file)
		if err == nil {
			return nil, img.Width, img.Height
		}

		return nil, 0, 0
	}

	return errors.New("not image mimetype"), 0, 0
}
